<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useProductStore } from '@/stores/product'
import ProductCard from '@/components/ProductCard.vue'

const route = useRoute()
const router = useRouter()
const product = useProductStore()
const pageNo = ref(1)
const pageSize = ref(12)
const currentCategory = ref<number | undefined>(undefined)
const q = ref<string>('')

onMounted(async () => {
  await product.fetchCategories()
  const rq = (route.query.q as string) || ''
  q.value = rq
  await load()
})

watch(() => route.query.q, (val) => {
  q.value = (val as string) || ''
  load()
})

async function load() {
  await product.fetchProducts({ pageNo: pageNo.value, pageSize: pageSize.value, name: q.value, categoryId: currentCategory.value })
}

function selectCategory(id?: number) {
  currentCategory.value = id
  load()
}

function toCategory() {
  router.push({ name: 'category' })
}
</script>

<template>
  <div class="container">
    <section class="cats" v-if="product.categories.length">
      <button :class="{ active: !currentCategory }" @click="selectCategory()">全部</button>
      <button v-for="c in product.categories" :key="c.id" :class="{ active: currentCategory === c.id }" @click="selectCategory(c.id)">{{ c.name }}</button>
      <button class="more" @click="toCategory">更多分类</button>
    </section>

    <section class="grid">
      <ProductCard v-for="p in product.products" :key="p.id" :item="p" />
    </section>
  </div>
</template>

<style scoped>
.cats { display: flex; gap: 8px; margin: 12px 0; flex-wrap: wrap; }
.cats button { padding: 8px 12px; border: 1px solid #ddd; background: #fff; border-radius: 16px; }
.cats button.active { color: #fff; background: #42b883; border-color: #42b883; }
.cats .more { margin-left: auto; }
.grid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 16px; }
@media (max-width: 1280px){ .grid { grid-template-columns: repeat(4, 1fr); } }
@media (max-width: 960px){ .grid { grid-template-columns: repeat(3, 1fr); } }
@media (max-width: 720px){ .grid { grid-template-columns: repeat(2, 1fr); } }
</style>
